package com.pansoft.nfc;

import android.app.Activity;
import android.content.Context;

import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.CardBean;
import com.pansoft.openplanet.bean.CardWalletInfo;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.db.CardDao;
import com.pansoft.openplanet.util.TCAccountManager;

import java.util.ArrayList;
import java.util.List;

public class NfcWalletDeleteManager {

    private INfcDeleteWalletListener listener;

    public NfcWalletDeleteManager() {
    }

    public void deleteFromServer(final Context context, String address, CardBean cardBean,
                                 String cardInfo) {
        final AccountDao accountDao = new AccountDao(context);
        final Account account = accountDao.getAccount(address);
        if (account == null) {
            //仅本地
            if (listener != null) {
                listener.onDeleteFromServerSuccess();
            }
            return;
        }
        if (new TCAccountManager(context).deleteCardWallet(account.getAddress(), cardBean.getUid(),
                cardInfo)) {
            accountDao.delete(account.getAddress());
            if (listener != null) {
                listener.onDeleteFromServerSuccess();
            }
        } else {
            ((Activity)context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.showToast(context,
                            ResStringUtil.getString(R.string.common_text_delete_fails));
                }
            });
        }
    }

    /**
     * 从本地数据库card表中删除钱包
     */
    private void deleteWalletFromCardDb(int position, CardBean cardBean, CardDao cardDao,
                                        List<CardWalletInfo> cardWalletInfoList) {
        List<CardWalletInfo> cardWalletInfos = new ArrayList<>();
        for (CardWalletInfo c :
                cardWalletInfoList) {
            if (c.getInCardPosition() != position) {
                cardWalletInfos.add(c);
            }
        }
        cardBean.setWalletInfoList(cardWalletInfos);
        cardBean.setEnable(true);
        cardDao.insertOrReplace(cardBean);
    }

    public interface INfcDeleteWalletListener{
        void onDeleteFromServerSuccess();
    }

    public void setINfcDeleteWalletListener(INfcDeleteWalletListener iNfcDeleteWalletListener) {
        this.listener = iNfcDeleteWalletListener;
    }


}
